﻿using DataProcesss;
using DataProcesss.model;
using Microsoft.Win32;
using Parylene_CVD.Commands;
using Parylene_CVD.DAL;
using Parylene_CVD.Model;
using Parylene_CVD.Service;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Parylene_CVD.ViewModel
{
    public class DataRecordViewModel : ViewModelBase
    {
        public DataRecordViewModel(NavigationService DeviceMonitorViewNavigationService, NavigationService DataCurveViewNavigationService, NavigationService AlarmEventViewNavigationService, NavigationService HomeViewNavigationService) {
            MonitorCommand = new NavigateCommand(DeviceMonitorViewNavigationService);
            DataCurveCommand = new NavigateCommand(DataCurveViewNavigationService);
            AlarmEventCommand = new NavigateCommand(AlarmEventViewNavigationService);
            ExitCommand = new NavigateCommand(HomeViewNavigationService);
            ComboBoxCommand = new DelegateCommand<Object>(ComboBoxSelectionChanged);
            NextPageCmd = new DelegateCommand(NextPage);
            PreviousPageCmd = new DelegateCommand(PreviousPage);
            LastPageCmd = new DelegateCommand(LastPage);
            FirstPageCmd = new DelegateCommand(FirstPage);
            DeviceName = GlobalVariables.CurDeviceName;
            DataSource = new ObservableCollection<Data>();
            OpenFileDialogCommand = new RelayCommand(OpenFileDialog);
            UpdateStartTimeCommand = new RelayCommand(UpdateStartTime);
            StartTime = DateTime.Now;
            EndTime = DateTime.Now;
            SetDefaultFolderPath();
            TitleSet();
        }


        public ICommand? MonitorCommand { get; }
        public ICommand? DataRecordCommand { get; }
        public ICommand? DataCurveCommand { get; }
        public ICommand? AlarmEventCommand { get; }
        public ICommand? ExitCommand { get; }

       
        // 设备名
        private string? _deviceName;
        public string? DeviceName
        {
            get => _deviceName;
            set
            {
                _deviceName = value;
                OnPropertyChanged(nameof(DeviceName));
            }
        }
        //根据开始结束时间在文件中获取的数据
        private ObservableCollection<Data> _dataSource;
        public ObservableCollection<Data> DataSource
        {
            get { return _dataSource; }
            set
            {
                _dataSource = value;
                OnPropertyChanged("DataSource");
            }
        }


        /// <summary>
        /// 页容量初始化
        /// </summary>
        public int pagesize = 10;
        /// <summary>
        /// 最后一页事件
        /// </summary>
        public DelegateCommand LastPageCmd { get; private set; }
        /// <summary>
        /// 第一页事件
        /// </summary>
        public DelegateCommand FirstPageCmd { get; private set; }
        /// <summary>
        /// 上一页事件
        /// </summary>
        public DelegateCommand PreviousPageCmd { get; private set; }
        /// <summary>
        /// 下一页事件
        /// </summary>
        public DelegateCommand NextPageCmd { get; private set; }


        /// <summary>
        /// 下拉事件
        /// </summary>
        public DelegateCommand<Object> ComboBoxCommand { get; private set; }
        /// <summary>
        /// 第几页
        /// </summary>
        private int pageNumber;

        public int PageNumber
        {
            get { return pageNumber; }
            set
            {
                pageNumber = value;
                OnPropertyChanged(nameof(PageNumber));
            }
        }
        /// <summary>
        /// 记录条数
        /// </summary>
        private int totalRecord;

        public int TotalRecord
        {
            get { return totalRecord; }
            set
            {
                totalRecord = value;
                OnPropertyChanged(nameof(TotalRecord));
            }
        }
        /// <summary>
        /// 总页数
        /// </summary>
        private int totalPage;

        public int TotalPage
        {
            get { return totalPage; }
            set
            {
                totalPage = value;
                OnPropertyChanged(nameof(TotalPage));
            }
        }

        /// <summary>
        /// 是否可以执行上一页
        /// </summary>
        private bool canPrevious;

        public bool CanPrevious
        {
            get { return canPrevious; }
            set
            {
                canPrevious = value;
                OnPropertyChanged(nameof(CanPrevious));
            }
        }
        /// <summary>
        /// 是否可以执行上一页
        /// </summary>
        private bool canNext;

        public bool CanNext
        {
            get { return canNext; }
            set
            {
                canNext = value;
                OnPropertyChanged(nameof(CanNext));
            }
        }


        /// <summary>
        /// 分页后的数据
        /// </summary>
        private ObservableCollection<Data> datas;
        public ObservableCollection<Data> Datas
        {
            get { return datas; }
            set { datas = value; OnPropertyChanged(nameof(Datas)); }
        }


        private void FirstPage()
        {
            PageNumber = 1; //增加一页
            CanPrevious = false;
            if (pageNumber > 1)
            {
                CanPrevious = true; //是否可以点击上一页 否
            }
            TotalRecord = _dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > PageNumber)
            {
                CanNext = true;//是否可以点击下一页
            }
            else
            {
                CanNext = false;
            }
            Datas = new ObservableCollection<Data>();
            var data = _dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Datas.Add(item);
            }
        }

        /// <summary>
        /// 最后一页
        /// </summary>
        private void LastPage()
        {
            CanPrevious = false;
            TotalRecord = _dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            PageNumber = TotalPage;//最后一页 将总页码赋值给当前页
            if (pageNumber > 1)
            {
                CanPrevious = true; //是否可以点击上一页 否
            }
            if (TotalPage > PageNumber)
            {
                CanNext = true;//是否可以点击下一页
            }
            else
            {
                CanNext = false;
            }
            Datas = new ObservableCollection<Data>();
            var data = _dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Datas.Add(item);
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        private void NextPage()
        {
            PageNumber++; //增加一页
            CanPrevious = false;
            if (pageNumber > 1)
            {
                CanPrevious = true; //是否可以点击上一页 否
            }
            TotalRecord = _dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > PageNumber)
            {
                CanNext = true;//是否可以点击下一页
            }
            else
            {
                CanNext = false;
            }
            Datas = new ObservableCollection<Data>();
            var data = _dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Datas.Add(item);
            }
        }

        private void PreviousPage()
        {
            PageNumber--; //增加一页
            CanPrevious = false;
            if (pageNumber > 1)
            {
                CanPrevious = true; //是否可以点击上一页 否
            }
            TotalRecord = _dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > PageNumber)
            {
                CanNext = true;//是否可以点击下一页
            }
            else
            {
                CanNext = false;
            }
            Datas = new ObservableCollection<Data>();
            var data = _dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Datas.Add(item);
            }
        }

        /// <summary>
        /// 选择每页显示记录数
        /// </summary>
        /// <param name="obj"></param>
        private void ComboBoxSelectionChanged(Object obj)
        {
            if (obj != null)
            {
                var Content = ((System.Windows.Controls.ContentControl)obj).Content;
                switch (Content)
                {
                    case "10条/页": pagesize = 10; ComboBoxSelectionInitData(); break;
                    case "20条/页": pagesize = 20; ComboBoxSelectionInitData(); break;
                    case "30条/页": pagesize = 30; ComboBoxSelectionInitData(); break;
                }
            }
        }
        /// <summary>
        /// 每页显示记录数改变时 重新加载数据
        /// </summary>
        void ComboBoxSelectionInitData()
        {
            //
            PageNumber = 1; //页码改变时 加载第一页
            CanPrevious = false; //是否可以点击上一页 否
            TotalRecord = _dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > 1)
            {
                CanNext = true;//是否可以点击下一页
            }
            Datas = new ObservableCollection<Data>();
            var data = _dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Datas.Add(item);
            }
        }

        public void CreateDatas()
        {
            PageNumber = 1; //默认加载第一页
            CanPrevious = false; //是否可以点击上一页 否
            TotalRecord = _dataSource.Count; //总记录数
            int pages = TotalRecord / pagesize;
            TotalPage = TotalRecord % pagesize == 0 ? pages : pages + 1; //总页数
            if (TotalPage > 1)
            {
                CanNext = true;//是否可以点击下一页
            }
            Datas = new ObservableCollection<Data>();
            var data = _dataSource.Skip((PageNumber - 1) * pagesize).Take(pagesize);
            foreach (var item in data)
            {
                Datas.Add(item);
            }
        }

        //创建读取文件数据对象
        RealtimeData datasave = new RealtimeData();
        //点击确认按钮执行命令
        public ICommand UpdateStartTimeCommand { get; private set; }
        //点击确认按钮执行方法，如果开始时间小于结束时间弹出提示框，否则根据时间段更新数据
        private void UpdateStartTime(object obj)
        {
            if (_startTime < _endTime)
            {
                DataSource = datasave.GetData(FilePath);
                DataSelectFromTime(DataSource,StartTime,EndTime);
                CreateDatas();
            }
            else
            {
                MessageBox.Show($"结束时间不能小于开始时间");
            }
        }
        //开始时间
        private DateTime _startTime;
        public DateTime StartTime
        {
            get { return _startTime; }
            set
            {
                _startTime = value;
                OnPropertyChanged("StartTime");
            }
        }
        //结束时间
        private DateTime _endTime;
        public DateTime EndTime
        {
            get { return _endTime; }
            set
            {
                _endTime = value;
                OnPropertyChanged("EndTime");
            }
        }

        //文件完整路径
        public string _FilePath;
        public string FilePath
        {
            get { return _FilePath; }
            set { _FilePath = value; OnPropertyChanged(nameof(FilePath)); }
        }
        //文件名
        private string _selectedFileName;
        public string SelectedFileName
        {
            get => _selectedFileName;
            set
            {
                _selectedFileName = value;
                OnPropertyChanged(nameof(SelectedFileName));
            }
        }

        // 默认文件夹路径--->通常为数据库中存储路径拼接当前设备名
        public string DefaultFolderPath { get; set; }
        public void SetDefaultFolderPath()
        {
            ParameterDAL parameterDAL = new ParameterDAL();
            string BasePath = parameterDAL.GetParameter("ParameterName = '数据保存目录'", "")[0].ParameterValue;
            DefaultFolderPath = System.IO.Path.Combine(BasePath, DeviceName);
        }
        //选择文件按钮命令
        public ICommand OpenFileDialogCommand { get; }
        // 选择文件执行方法
        private void OpenFileDialog(object obj)
        {
            RealtimeData datasave = new RealtimeData();
            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = DefaultFolderPath, // 默认打开的文件夹路径
            };

            if (openFileDialog.ShowDialog() == true)
            {
                // 获取选择的文件路径
                FilePath = openFileDialog.FileName;
                // 获取文件名（不包括路径和扩展名）
                SelectedFileName = System.IO.Path.GetFileNameWithoutExtension(FilePath);
                DataSource = datasave.GetData(FilePath);
                StartTime = DateTime.Parse(DataSource[0].Time);
                EndTime = DateTime.Parse(DataSource[DataSource.Count - 1].Time);
                
                DataSelectFromTime(DataSource, StartTime, EndTime);
                CreateDatas();
                

            }
        }

        /// <summary>
        /// 根据数据源和开始结束时间获得时间区间内的数据
        /// </summary>
        /// <param name="DataSource"></param>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        public void DataSelectFromTime(ObservableCollection<Data> OriginDataSource, DateTime StartTime, DateTime EndTime)
        {
            // 将开始时间和结束时间转换为字符串
            string startTimeStr = StartTime.ToString("yyyy-MM-dd HH:mm:ss");
            string endTimeStr = EndTime.ToString("yyyy-MM-dd HH:mm:ss");
            DataSource = datasave.DataSelect(OriginDataSource, startTimeStr, endTimeStr);
        }


        public string Start_Title { get; set; }
        public string End_Title { get; set; }
        
        public string Confirm_Title { get; set; }
        
        private void TitleSet()
        {
            Start_Title = "开始:";
            End_Title = "结束:";
            Confirm_Title = "确认";
        }
    }
}
